<?php

namespace App\V3\V3_2_7\Controllers;
use App\Http\Controllers\Controller;
use App\V3\V3_2_7\Models\AdminModel;
use App\V3\V3_2_7\Models\PddSellerCodeListModel;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Justmd5\PinDuoDuo\PinDuoDuo;
use function AlibabaCloud\Client\json;
use Illuminate\Http\Request;

Class PingDuoDuoAuthorizationController extends Controller {
    protected $pinDuoDuo;
    protected $token;
    public function __construct(Request $request){
        $config = [
            'client_id'    => 'd75a149f595347679b0d00b83671edd7',
            'client_secret' => '2fbd0b4ce8b82ff53cdaaf7e0231f6abc11cd624',
            'debug'              => true,
            'member_type'        => 'MERCHANT',//用户角色 ：MERCHANT(商家授权),H5(移动端),多多客(JINBAO),
            'redirect_uri'       => 'https://'.$_SERVER['SERVER_NAME'].'/'.$_SERVER['REQUEST_URI'],
            'log'                => [
                'name'       => 'pinduoduo',
                'file'       => __DIR__ . '/pinduoduo.log',
                'level'      => 'debug',
                'permission' => 0777,
            ],
        ];
        $this->pinDuoDuo = new PinDuoDuo($config);
    }

    /**
     * 商家授权
     */
    public function pddSellerAuthorizationCode(Request $request){

        $validator = Validator::make($data=$request->all(), [
            'code' => 'required',//商家授权code
            'state' => [
                'required',
                'integer|min:0',
            ]//商家在睡猫云仓id
        ], [
                'code.required' => '商家授权code,不能为空',
                'state.required' => '`state`参数，不能为空',
                'state.integer' => '`state`参数的值，必须为整数。',
                'state.min' => '`state`参数的值，必须大于0',
            ]);
        $res = $this->pinDuoDuo->pre_auth->getAccessToken($request->code);
        if(isset($res['error_code'])){
            return response()->json(['code'=>1,'msg'=>$res['error_msg'],'data'=>'']);
        }
        $this->pinDuoDuo->access_token->setToken($res['access_token']);
        $this->token = $this->pinDuoDuo->access_token->getToken();
        $sellerArray = [
            'code'=>$data['code'] ?? '',
            'access_token'=>$res['access_token'] ?? '',
            'refresh_token'=>$res['refresh_token'] ?? '',
        ];
        Redis::SETEX('pdd_seller_access_token', 86400*23, json_encode($sellerArray));
        $adminInfo = AdminModel::where([
            'id'=>$data['state'],
            'delete_flag'=>0,
            'is_active'=>1
        ])->first();
         if(empty($adminInfo)){
             return response()->json(['code'=>1,'msg'=>'没有找到和睡猫云仓关联账号！','data'=>'']);
         }
        PddSellerCodeListModel::updateOrInsert([
            'main_id'=>!empty($adminInfo['parent_id'])?$adminInfo['parent_id']:$adminInfo['id'],
        ],
        array_merge([
            'main_id'=>!empty($adminInfo['parent_id'])?$adminInfo['parent_id']:$adminInfo['id'],
            'user_id'=>$adminInfo['id'],
            'created_at'=>time()
        ],
        $sellerArray));
        return response()->json(['code'=>0,'msg'=>'success','data'=>'']);
    }
}
